package com.jdy.haoduoai.activity;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.Drawable;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v4.content.ContextCompat;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.iflytek.cloud.ErrorCode;
import com.iflytek.cloud.InitListener;
import com.iflytek.cloud.SpeechConstant;
import com.iflytek.cloud.SpeechError;
import com.iflytek.cloud.SpeechSynthesizer;
import com.iflytek.cloud.SpeechUtility;
import com.iflytek.cloud.SynthesizerListener;
import com.jdy.haoduoai.LeXiaoXiaoBanApp;
import com.jdy.haoduoai.adapter.MyStoryAdapter;
import com.jdy.haoduoai.adapter.OnPreviewClickListener;
import com.jdy.haoduoai.adapter.RadioCategoryGridViewAdapter;
import com.jdy.haoduoai.audioconverter.AndroidAudioConverter;
import com.jdy.haoduoai.audioconverter.callback.IConvertCallback;
import com.jdy.haoduoai.audioconverter.model.AudioFormat;
import com.jdy.haoduoai.intface.IAsyncTask;
import com.jdy.haoduoai.model.AlbumItem;
import com.jdy.haoduoai.model.CategoryItem;
import com.jdy.haoduoai.model.ImageItem;
import com.jdy.haoduoai.model.LeHotDynamicItem;
import com.jdy.haoduoai.model.LeHotDynamicItemWrapper;
import com.jdy.haoduoai.model.LeUser;
import com.jdy.haoduoai.model.PainPointItem;
import com.jdy.haoduoai.model.RadioCategoryItem;
import com.jdy.haoduoai.parse.JsonSerializer;
import com.jdy.haoduoai.rx.util.async.Async;
import com.jdy.haoduoai.util.ACache;
import com.jdy.haoduoai.util.CustomAsyncTask;
import com.jdy.haoduoai.util.HttpUtils;
import com.jdy.haoduoai.util.ImageDisplayer;
import com.jdy.haoduoai.util.IntentConstants;
import com.jdy.haoduoai.util.ResponseResult;
import com.jdy.haoduoai.util.Tools;
import com.jdy.haoduoai.view.MyGridView;
import com.jdy.haoduoai.view.VisualizerView;
import com.jdy.haoduoai.widget.CustomTimeDialog;
import com.squareup.picasso.Picasso;
import com.ycsj.goldmedalnewconcept.R;

import org.droidparts.annotation.inject.InjectView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import rx.functions.Action0;
import rx.functions.Action1;
import rx.functions.Func0;
import rx.functions.Func1;

//import com.jdy.haoduoai.R;


/**
 * Created by Administrator on 2017/4/12 0012.
 */

public class AddHabitClockActivity extends BaseActivity implements View.OnClickListener {

    private static final String TAG = AddHabitClockActivity.class.getSimpleName();

    private RadioCategoryGridViewAdapter mRCGVAdapter;

    private enum SelectedEnum {
        None,
        CustomContent,
        Recording,
        StoryBabysong,
        MineStory,
    }

    private SelectedEnum mCurrentSelectedEnum = SelectedEnum.CustomContent;


    @InjectView(id = R.id.selected_img)
    private ImageView mSelectedImg;
    @InjectView(id = R.id.img_emptystory)
    private ImageView img_emptystory;
    @InjectView(id = R.id.custom_btn, click = true)
    private Button mCustomBtn;

    @InjectView(id = R.id.recoding_btn, click = true)
    private Button mRecordingBtn;

    @InjectView(id = R.id.lin_trylisten, click = true)
    private LinearLayout lin_trylisten;

    @InjectView(id = R.id.story_babysong_btn, click = true)
    private Button mStoryBabysongBtn;

    @InjectView(id = R.id.my_story_btn, click = true)
    private Button mMineStoryBtn;


    @InjectView(id = R.id.tts_content_et)
    private EditText mTtsContentEt;

    @InjectView(id = R.id.save_and_upload_btn, click = true)
    private Button mSaveUploadBtn;

    @InjectView(id = R.id.record_state_btn, click = true)
    private Button mRecordStateBtn;

    @InjectView(id = R.id.retry_record_tv, click = true)
    private TextView mRetryTv;

    @InjectView(id = R.id.title_et)
    private EditText mTitleEt;

    @InjectView(id = R.id.set_timer_img, click = true)
    private ImageView mSetTimerImg;

    @InjectView(id = R.id.set_timer_tv, click = true)
    private TextView mSetTimerTv;

    @InjectView(id = R.id.add_pic_img, click = true)
    private ImageView mAddThemePicImg;

    @InjectView(id = R.id.preview_listen_caption_tv, click = true)
    private TextView mPreviewListenTv;

    @InjectView(id = R.id.preview_record_img, click = true)
    private ImageView mPreviewImg;

    @InjectView(id = R.id.preview_record_img2)
    private ImageView mPreviewImg2;


    @InjectView(id = R.id.recording_tip_tv)
    private TextView mRecordingTipTv;

    @InjectView(id = R.id.rel_storysong_item)
    private RelativeLayout rel_storysong_item;

    private CustomTimeDialog timeDlg;

    private SpeechSynthesizer mTts;

    // 缓冲进度
    private int mPercentForBuffering = 0;

    // 播放进度
    private int mPercentForPlaying = 0;

    // 默认发音人
    private String voicer = "nannan";


    // 引擎类型
    private String mEngineType = SpeechConstant.TYPE_CLOUD;

    private Toast mToast;

    @InjectView(id = R.id.record_visualizer)
    private VisualizerView mRecordVisualizerView;

    private MediaRecorder mRecorder = null;

    private File audioDirTemp;

    private boolean isRecording = false;

    private Handler mHandler; // Handler for updating the visualizer

    public static final String DIRECTORY_NAME_TEMP = "AudioTemp";

    public static final int REPEAT_INTERVAL = 15;

    private enum RecordingState {
        PRE_RECORDING,

        RECORDING,

        STOP_RECORDING,
    }

    private RecordingState RECORING_STATE = RecordingState.PRE_RECORDING;

    private String RECORDING_AUDIO_PATH = "";

    private String TTS_AUDIO_PATH = "";

    private MediaPlayer mp3Player;

    private LeUser leUser;

    private String LOCAL_HABIT_IMAGE = "";

    private boolean isEdit, tryListenOnline;
    private PainPointItem mPainPointItem;

    private AnimationDrawable mAnim;

    @InjectView(id = R.id.my_story_listview)
    private ListView mMineStoryListView;
    @InjectView(id = R.id.bottom_gridview)
    private MyGridView mbottom_gridview;

    private ArrayList<LeHotDynamicItem> mAdapterList = null;

    private int mLastPage = 1;

    private LeHotDynamicItemWrapper mLeMyVoiceItemWrapper;

    private MyStoryAdapter mMineStoryAdapter;

    @InjectView(id = R.id.content_layout)
    private RelativeLayout mContentLayout;

    private ACache mCache;

    private List<RadioCategoryItem> mRadioCategoryList;

    private TextView mLastTv = null;

    private int mSelectedId = -1;

    private boolean mIsPreviewing = false;

    private void restoreContentLayoutHeight() {
        RelativeLayout.LayoutParams iParams = (RelativeLayout.LayoutParams) mContentLayout
                .getLayoutParams();

        iParams.height = Tools.getPixelByDip(this, 210);

//        iParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);

        mContentLayout.setLayoutParams(iParams);
    }

    private void parseJsonArray(String data) {
        try {
            JSONArray jsonArray = new JSONArray(data);
            int size = jsonArray.length();
            mRadioCategoryList.clear();
            for (int i = 0; i < size; i++) {
                JSONObject jo = (JSONObject) jsonArray.get(i);
                String name = jo.getString("name");
                if (name.equals("情景")) {
                    // TODO
                } else if (name.equals("年龄")) {
                    // TODO
                } else {
                    RadioCategoryItem rci = JsonSerializer.getInstance().deserialize(
                            jo.toString(), RadioCategoryItem.class);
                    mRadioCategoryList.add(rci);
                }
            }
            setRadioCategoryView();
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private void loadCategoryData() {
        String data = mCache.getAsString("RadioStationActivityloadCategoryData");
        if (Tools.isNotEmpty(data)) {
            parseJsonArray(data);
        } else {
            new CustomAsyncTask(this, new IAsyncTask() {
                @Override
                public void onRecieveData(Activity activity, ResponseResult result) {
                    if (result.isSuccess()) {
                        if (Tools.isNotEmpty(result.data)) {
                            mCache.remove("RadioStationActivityloadCategoryData");
                            mCache.put("RadioStationActivityloadCategoryData", result.data,
                                    2 * ACache.TIME_DAY);

                            parseJsonArray(result.data);
                        }
                    }
                }

                @Override
                public ResponseResult doInbackground(Activity activity) {
                    LeUser lu = LeXiaoXiaoBanApp.getInstance().getUser();
                    if (lu == null) {
                        lu = Tools.restoreLeUser();
                    }

                    HashMap<String, Object> param_ = new HashMap<String, Object>();
                    param_.put("sno", lu.sno);
                    param_.put(HttpUtils.TAG_KEY_I, HttpUtils.KEY);

                    return HttpUtils.startRequest(HttpUtils.API_URL
                                    + "/api/2.0/catalog/radio/collection", param_,
                            HttpUtils.TAG_GET_REQUEST);

                }
            }).execute();
        }
    }

    private void setContentLayoutToWrapHeight() {
        RelativeLayout.LayoutParams iParams = (RelativeLayout.LayoutParams) mContentLayout
                .getLayoutParams();
        iParams.height = ViewGroup.LayoutParams.WRAP_CONTENT;
        mContentLayout.setLayoutParams(iParams);
    }

    private void startAnimation(TextView tv) {
        if (tv != null) {
            AnimationDrawable ad = (AnimationDrawable) ContextCompat.getDrawable(this, R.drawable.preview_anim);
            tv.setCompoundDrawablesWithIntrinsicBounds(null, null, ad, null);
            ad.start();
        }
    }

    private void stopAnimation(TextView tv) {
        if (tv != null) {

            Drawable[] drawables = tv.getCompoundDrawables();

            Drawable rightD = drawables[2];

            if (rightD instanceof AnimationDrawable) {
                AnimationDrawable ad = (AnimationDrawable) rightD;

                if (ad != null && ad.isRunning()) {
                    ad.stop();
                }

                Drawable d = ContextCompat.getDrawable(this, R.drawable.preview_record_img);

                tv.setCompoundDrawablesWithIntrinsicBounds(null, null, d, null);

            } else {
                return;
            }
        }
    }


    private void startAnimation() {
        mPreviewImg.setImageResource(R.drawable.preview_anim);
        mAnim = (AnimationDrawable) mPreviewImg.getDrawable();
        mAnim.start();
    }

    private void stopAnimation() {
        if (mAnim != null && mAnim.isRunning()) {
            mAnim.stop();
        }
        mPreviewImg.setImageResource(R.drawable.preview_record_img);
    }

    private void stopAnimation2() {
        if (mAnim != null && mAnim.isRunning()) {
            mAnim.stop();
        }
        mPreviewImg2.setImageResource(R.drawable.preview_record_img);

        mIsPreviewingStorySong = false;
    }


    private void loadDataAsync(boolean isShow) {
        if (mAdapterList != null && !mAdapterList.isEmpty()) {
            mAdapterList.clear();
        }

        if (isShow) {
            showloading("");
        }

        Async.start(new Func0<ResponseResult>() {
            @Override
            public ResponseResult call() {
                HashMap<String, Object> param_ = new HashMap<String, Object>();
                param_.put(HttpUtils.TAG_SNO_I, leUser.sno);
                param_.put(HttpUtils.TAG_KEY_I, HttpUtils.KEY);
                param_.put("member_id", leUser.id);
                param_.put("page", mLastPage);

                return HttpUtils.startRequest(
                        HttpUtils.API_URL + "/api/2.0/member/dub", param_,
                        HttpUtils.TAG_GET_REQUEST);
            }
        }).filter(new Func1<ResponseResult, Boolean>() {
            @Override
            public Boolean call(ResponseResult arg0) {
                return arg0 != null && Tools.isNotEmpty(arg0) && arg0.isSuccess();
            }
        }).doOnCompleted(new Action0() {
            @Override
            public void call() {
                Message message = new Message();
                message.what = mLastPage;
                if (handler != null) {
                    handler.sendMessage(message);
                }
                mLastPage++;
            }
        }).subscribe(new Action1<ResponseResult>() {
            @Override
            public void call(ResponseResult arg0) {
                mLeMyVoiceItemWrapper = JsonSerializer.getInstance().deserialize(
                        arg0.data, LeHotDynamicItemWrapper.class);

                mAdapterList.addAll(mLeMyVoiceItemWrapper.data);

                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        Tools.setListViewHeightBasedOnChildren(mMineStoryListView);
                    }
                }, 1000);
//                mMineStoryAdapter.notifyDataSetChanged();
            }
        });

    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.add_habit_layout);
        SpeechUtility.createUtility(AddHabitClockActivity.this, "appid=" + "574e86a0");
        leUser = LeXiaoXiaoBanApp.getInstance().getUser();
        this.titleLayout.setBackgroundColor(Color.argb(255, 255, 255, 255));
        this.mBackImageButton.setImageResource(R.drawable.black_back);
        this.mTvUpright.setText("完成");
        this.mTvUpright.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                publishCustomHabit();
            }
        });
        this.mTvUpright.setVisibility(View.VISIBLE);
        this.mTvUpright.setTextColor(Color.argb(255, 19, 19, 19));

        mCache = ACache.get(this);
        mRadioCategoryList = new ArrayList<RadioCategoryItem>();

        this.mTitleText.setTextColor(Color.argb(255, 19, 19, 19));
        this.mRetryTv.setPaintFlags(mRetryTv.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG);

        mTts = SpeechSynthesizer.createSynthesizer(AddHabitClockActivity.this, mTtsInitListener);

        mToast = Toast.makeText(this, "", Toast.LENGTH_SHORT);

        audioDirTemp = new File(Environment.getExternalStorageDirectory(),
                DIRECTORY_NAME_TEMP);
        if (audioDirTemp.exists()) {
            deleteFilesInDir(audioDirTemp);
        } else {
            audioDirTemp.mkdirs();
        }

        RECORDING_AUDIO_PATH = audioDirTemp + "/audio_file"
                + ".amr";


        TTS_AUDIO_PATH = Environment.getExternalStorageDirectory() + "/msc/tts.wav";


        File wavFile = new File(TTS_AUDIO_PATH);
        if (wavFile.exists()) {
            wavFile.delete();
        }

        File mp3File = new File(TTS_AUDIO_PATH.replace(".wav", ".mp3"));
        if (mp3File.exists()) {
            mp3File.delete();
        }


        // create the Handler for visualizer update
        handler = new Handler();

        List<ImageItem> incomingDataList = (List<ImageItem>) getIntent()
                .getSerializableExtra(IntentConstants.EXTRA_IMAGE_LIST);
        if (incomingDataList != null && incomingDataList.size() != 0) {
            ImageItem item = incomingDataList.get(0);
            LOCAL_HABIT_IMAGE = item.sourcePath;
            ImageDisplayer.getInstance(this).displayBmp(mAddThemePicImg,
                    item.sourcePath, item.sourcePath);
        }

        InputFilter[] filters = new InputFilter[1];

        filters[0] = new InputFilter.LengthFilter(10); //Filter to 10 characters

        mTitleEt.setFilters(filters);


        InputFilter[] filters2 = new InputFilter[1];

        filters2[0] = new InputFilter.LengthFilter(140); //Filter to 140 characters

        mTtsContentEt.setFilters(filters2);

        mTtsContentEt.addTextChangedListener(new TextWatcher() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.toString().length() > 140)
                    showTip("最多不超过140个字.");
            }
        });

        mp3Player = new MediaPlayer();

        Intent it = getIntent();
        if (it != null) {
            isEdit = it.getBooleanExtra("isedit", false);
            mPainPointItem = (PainPointItem) it.getSerializableExtra("custompainpoint");
        }

        if (isEdit && mPainPointItem != null) {
            Picasso.with(this).load(mPainPointItem.img).into(mAddThemePicImg);
            mTitleEt.setText(mPainPointItem.name);
            int lastIdx = mPainPointItem.time.lastIndexOf(":");
            mSetTimerTv.setText(mPainPointItem.time.substring(0, lastIdx));
            this.mTitleText.setText("编辑习惯");
            LOCAL_HABIT_IMAGE = mPainPointItem.img;
            imgUrl_toSubmit = mPainPointItem.img;
            if (Tools.isNotEmpty(mPainPointItem.mp3_url)) {
                tryListenOnline = true;
                mp3url_Online = mPainPointItem.mp3_url;
            }
        } else {
            this.mTitleText.setText("添加习惯");
        }

        mAdapterList = new ArrayList<LeHotDynamicItem>();

        mMineStoryAdapter = new MyStoryAdapter(this, mAdapterList);

        mMineStoryAdapter.setOnPreviewClickListener(new OnPreviewClickListener() {
            @Override
            public void onPreviewClick(TextView tv, int id, String mp3_url) {
//                showTip("预览" + id);
                if (id != mSelectedId) {
                    stopAnimation(mLastTv);
                    startAnimation(tv);
                    mIsPreviewing = true;
                    previewMp3(mp3_url);
                } else {
                    mIsPreviewing = !mIsPreviewing;
                    if (mIsPreviewing) {
                        startAnimation(tv);
                        previewMp3(mp3_url);
                    } else {
                        stopAnimation(tv);
                        releaseMp3Player();
                    }
                }
                mLastTv = tv;
                mSelectedId = id;
            }
        });


        mMineStoryListView.setAdapter(mMineStoryAdapter);

        loadDataAsync(false);

        mMineStoryListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                mMineStoryAdapter.selected_position = position;
                mMineStoryAdapter.notifyDataSetChanged();
                ldi = mAdapterList.get(position);
                mp3url_toSubmit = ldi.av;
                showTip("故事" + ldi.id + "被选中!");
            }
        });

        loadCategoryData();
    }

    LeHotDynamicItem ldi;

    private void previewMp3(String mp3_url) {
        releaseMp3Player();

        boolean excepthappen = false;
        if (mp3Player == null)
            mp3Player = new MediaPlayer();
        try {
            mp3Player.setDataSource(mp3_url);
        } catch (IllegalArgumentException e) {
            excepthappen = true;
            e.printStackTrace();
        } catch (SecurityException e) {
            excepthappen = true;
            e.printStackTrace();
        } catch (IllegalStateException e) {
            excepthappen = true;
            e.printStackTrace();
        } catch (IOException e) {
            excepthappen = true;
            e.printStackTrace();
        }

        if (!excepthappen) {
            try {
                mp3Player.prepare();
                mp3Player.start();
                mp3Player.setOnCompletionListener(mediaPlayerListener);
            } catch (IllegalArgumentException e) {
                excepthappen = true;
                e.printStackTrace();
            } catch (SecurityException e) {
                excepthappen = true;
                e.printStackTrace();
            } catch (IllegalStateException e) {
                excepthappen = true;
                e.printStackTrace();
            } catch (IOException e) {
                excepthappen = true;
                e.printStackTrace();
            }
        } else {
            toastShow("暂时无法试听");
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        setIntent(intent);
        processExtraData();
        super.onNewIntent(intent);
    }

    private void processExtraData() {
        Intent intent = getIntent();
        if (intent != null) {
            List<ImageItem> incomingDataList = (List<ImageItem>) getIntent()
                    .getSerializableExtra(IntentConstants.EXTRA_IMAGE_LIST);
            if (incomingDataList != null && incomingDataList.size() != 0) {
                ImageItem item = incomingDataList.get(0);
                LOCAL_HABIT_IMAGE = item.sourcePath;
                ImageDisplayer.getInstance(this).displayBmp(mAddThemePicImg,
                        item.sourcePath, item.sourcePath);
            }
        }
    }

    public static boolean deleteFilesInDir(File path) {

        if (path.exists()) {
            File[] files = path.listFiles();
            if (files == null) {
                return true;
            }
            for (int i = 0; i < files.length; i++) {

                if (files[i].isDirectory()) {

                } else {
                    files[i].delete();
                }
            }
        }
        return true;
    }

    private CountDownTimer mCountDownTimer;

    private void startCountdownTimer() {
        mCountDownTimer = new CountDownTimer(3 * 60 * 1000, 1000) {

            public void onTick(long millisUntilFinished) {

                //here you can have your logic to set text to edittext
            }

            public void onFinish() {
                showTip("录音时间不超过3分钟");
            }

        }.start();
    }

    private void stopCountdownTimer() {
        if (mCountDownTimer != null) {
            mCountDownTimer.cancel();
            mCountDownTimer = null;
        }
    }

    private CategoryItem convert2CI(RadioCategoryItem rci) {
        // TODO Auto-generated method stub
        CategoryItem ci = new CategoryItem();
        ci.id = rci.id;
        ci.name = rci.name;
        ci.code = rci.code;
        if (rci.enabled)
            ci.enabled = 1;
        else
            ci.enabled = 0;
        ci.sort = rci.sort;
        ci.created_at = rci.created_at;
        ci.updated_at = rci.updated_at;
        ci.deleted_at = rci.deleted_at;
        ci.icon = rci.icon;
        ci.catalog = rci.catalog;
        ci.home_page = rci.home_page;
        return ci;
    }

    private void setRadioCategoryView() {
        mRCGVAdapter = new RadioCategoryGridViewAdapter(this, mRadioCategoryList);
        mRCGVAdapter.setAddHabitMode(true);
        mbottom_gridview.setAdapter(mRCGVAdapter);
        mbottom_gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                CategoryItem categoryItem = convert2CI(mRadioCategoryList.get(position));
                Intent intent = new Intent();
                Bundle bundle = new Bundle();
                intent.setClass(AddHabitClockActivity.this, ExpandListActivity.class);
                bundle.putSerializable("categoryitem", categoryItem);
                intent.putExtras(bundle);
                startActivityForResult(intent, 1000);
            }
        });
    }

    private AlbumItem ai;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent returnedIntent) {
        super.onActivityResult(requestCode, resultCode, returnedIntent);

        switch (requestCode) {

            case 1000:
                if (resultCode == RESULT_OK) {

                    ai = (AlbumItem) returnedIntent.getExtras()
                            .getSerializable("selectdata");

                    mp3url_toSubmit = ai.url;
                    rel_storysong_item.setVisibility(View.VISIBLE);

                    final String album_name = ai.album_name;
                    final String name = ai.title;
                    final boolean isFav = ai.favorite;
                    final String order = ai.sort + "";
                    final String reslen = Tools.secToTime(ai.length);
                    final String subtitle = "";

                    TextView storynumber = (TextView)
                            findViewById(R.id.storynumber);
                    TextView storytittle = (TextView)
                            findViewById(R.id.storytittle);
                    TextView tv_storylist = (TextView)
                            findViewById(R.id.tv_storylist);

                    ImageView img_2222 = (ImageView) findViewById(R.id.img_2222);
                    Picasso.with(this).load(ai.album_cover).into(img_2222);

                    if (storynumber != null) {
                        storynumber.setText(album_name + " 第" + order + "集" + " ("
                                + reslen + ")");
                        if (Tools.isEmpty(subtitle)) {
                            storytittle.setText(name);
                        } else {
                            storytittle.setText(subtitle);
                        }
                    }
                }
                break;

        }
    }

    private void switchSelectState(SelectedEnum se) {
        switch (se) {
            case CustomContent:
                mSelectedImg.setImageResource(R.drawable.custom_content_selected);
                mSaveUploadBtn.setVisibility(View.VISIBLE);
                mRecordStateBtn.setVisibility(View.GONE);
                mRetryTv.setVisibility(View.GONE);
                mTtsContentEt.setVisibility(View.VISIBLE);
                mRecordingTipTv.setVisibility(View.GONE);
                mRecordVisualizerView.setVisibility(View.GONE);
                mMineStoryListView.setVisibility(View.GONE);
                img_emptystory.setVisibility(View.GONE);
                mbottom_gridview.setVisibility(View.GONE);
                rel_storysong_item.setVisibility(View.GONE);
                mPreviewImg.setVisibility(View.VISIBLE);
                mPreviewListenTv.setVisibility(View.VISIBLE);
                restoreContentLayoutHeight();
                break;
            case Recording:
                mSelectedImg.setImageResource(R.drawable.recoding_selected);
                mSaveUploadBtn.setVisibility(View.GONE);
                mRecordStateBtn.setVisibility(View.VISIBLE);
                mRetryTv.setVisibility(View.VISIBLE);
                mRecordVisualizerView.setVisibility(View.VISIBLE);
                mTtsContentEt.setVisibility(View.GONE);
                mRecordingTipTv.setVisibility(View.VISIBLE);
                mMineStoryListView.setVisibility(View.GONE);
                img_emptystory.setVisibility(View.GONE);
                mbottom_gridview.setVisibility(View.GONE);
                rel_storysong_item.setVisibility(View.GONE);
                mPreviewImg.setVisibility(View.VISIBLE);
                mPreviewListenTv.setVisibility(View.VISIBLE);
                restoreContentLayoutHeight();
                break;
            case StoryBabysong:
                mSelectedImg.setImageResource(R.drawable.story_babysong_selected);
                mRecordStateBtn.setVisibility(View.GONE);
                mRetryTv.setVisibility(View.GONE);
                mTtsContentEt.setVisibility(View.GONE);
                mRecordingTipTv.setVisibility(View.GONE);
                mRecordVisualizerView.setVisibility(View.GONE);
                mSaveUploadBtn.setVisibility(View.GONE);
                mPreviewImg.setVisibility(View.GONE);
                mPreviewListenTv.setVisibility(View.GONE);
                mMineStoryListView.setVisibility(View.GONE);
                img_emptystory.setVisibility(View.GONE);
                mbottom_gridview.setVisibility(View.VISIBLE);
                // rel_storysong_item.setVisibility(View.VISIBLE);
                restoreContentLayoutHeight();
                break;
            case MineStory:
                mSelectedImg.setImageResource(R.drawable.mine_story_selected);
                mRecordStateBtn.setVisibility(View.GONE);
                mRetryTv.setVisibility(View.GONE);
                mTtsContentEt.setVisibility(View.GONE);
                mRecordingTipTv.setVisibility(View.GONE);
                mRecordVisualizerView.setVisibility(View.GONE);
                mSaveUploadBtn.setVisibility(View.GONE);
                mPreviewImg.setVisibility(View.GONE);
                mPreviewListenTv.setVisibility(View.GONE);
                mMineStoryListView.setVisibility(View.VISIBLE);

                if (mAdapterList.isEmpty()) {
                    img_emptystory.setVisibility(View.VISIBLE);
                } else {
                    img_emptystory.setVisibility(View.GONE);
                }

                mbottom_gridview.setVisibility(View.GONE);
                rel_storysong_item.setVisibility(View.GONE);
                setContentLayoutToWrapHeight();
                break;
            default:
                break;
        }
    }

    private String mAiUrl;
    private boolean mIsPreviewingStorySong;

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.lin_trylisten:
                if (ai != null) {
                    releaseMp3Player();

                    if (Tools.isNotEmpty(mAiUrl) && !mAiUrl.equalsIgnoreCase(ai.url)) {
                        mIsPreviewingStorySong = true;

                        if (mp3Player == null)
                            mp3Player = new MediaPlayer();
                        try {
                            mp3Player.setDataSource(ai.url);
                            mp3Player.prepare();
                            mp3Player.start();
                            //  startAnimation();

                            mPreviewImg2.setImageResource(R.drawable.preview_anim);
                            mAnim = (AnimationDrawable) mPreviewImg2.getDrawable();
                            mAnim.start();

                            mp3Player.setOnCompletionListener(mediaPlayerListener2);
                        } catch (IllegalArgumentException e) {
                            e.printStackTrace();
                        } catch (SecurityException e) {
                            e.printStackTrace();
                        } catch (IllegalStateException e) {
                            e.printStackTrace();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    } else {
                        mIsPreviewingStorySong = !mIsPreviewingStorySong;
                        if (mIsPreviewingStorySong) {
                            if (mp3Player == null)
                                mp3Player = new MediaPlayer();
                            try {
                                mp3Player.setDataSource(ai.url);
                                mp3Player.prepare();
                                mp3Player.start();
                                //  startAnimation();

                                mPreviewImg2.setImageResource(R.drawable.preview_anim);
                                mAnim = (AnimationDrawable) mPreviewImg2.getDrawable();
                                mAnim.start();

                                mp3Player.setOnCompletionListener(mediaPlayerListener2);
                            } catch (IllegalArgumentException e) {
                                e.printStackTrace();
                            } catch (SecurityException e) {
                                e.printStackTrace();
                            } catch (IllegalStateException e) {
                                e.printStackTrace();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        } else {
                            stopAnimation2();
                            releaseMp3Player();
                        }
                    }
                    mAiUrl = ai.url;
                }

                break;
            case R.id.custom_btn:
                mCurrentSelectedEnum = SelectedEnum.CustomContent;

                switchSelectState(mCurrentSelectedEnum);
                break;
            case R.id.recoding_btn:
                mCurrentSelectedEnum = SelectedEnum.Recording;

                switchSelectState(mCurrentSelectedEnum);
                break;
            case R.id.story_babysong_btn:
                mCurrentSelectedEnum = SelectedEnum.StoryBabysong;
                switchSelectState(mCurrentSelectedEnum);
                break;
            case R.id.my_story_btn:
                mCurrentSelectedEnum = SelectedEnum.MineStory;
                switchSelectState(mCurrentSelectedEnum);
                break;

            case R.id.add_pic_img:
                Intent intent = new Intent(AddHabitClockActivity.this,
                        ImageBucketChooseActivity.class);
                intent.putExtra(IntentConstants.EXTRA_CAN_ADD_IMAGE_SIZE,
                        1);
                intent.putExtra("classFrom", AddHabitClockActivity.class.toString());
                startActivity(intent);
                break;
            case R.id.set_timer_tv:
            case R.id.set_timer_img:
                setHabitTime();
                break;
            case R.id.preview_record_img:
            case R.id.preview_listen_caption_tv:
                if (Tools.isNotEmpty(mTtsContentEt.getText().toString())) {
                    if (mCurrentSelectedEnum == SelectedEnum.CustomContent) {
                        tryListenOnline = false;
                    } else {
                        // TODO
                    }
                }

                if (tryListenOnline) {

                    releaseMp3Player();

                    if (mp3Player == null)
                        mp3Player = new MediaPlayer();
                    try {
                        mp3Player.setDataSource(mPainPointItem.mp3_url);
                        mp3Player.prepare();
                        mp3Player.start();
                        startAnimation();
                        mp3Player.setOnCompletionListener(mediaPlayerListener);
                    } catch (IllegalArgumentException e) {
                        e.printStackTrace();
                    } catch (SecurityException e) {
                        e.printStackTrace();
                    } catch (IllegalStateException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                } else {
                    if (mCurrentSelectedEnum == SelectedEnum.CustomContent) {
                        String text = mTtsContentEt.getText().toString();
                        if (Tools.isEmpty(text)) {
                            showTip("内容不能为空");
                            return;
                        }

                        if (text.length() > 140) {
                            showTip("最多不超过140个字");
                            return;
                        }

                        // 设置参数
                        setParam();
                        if (mp3Player != null && mp3Player.isPlaying()) {
                            releaseMp3Player();
                        }
                        int code = mTts.startSpeaking(text, mTtsListener);

                        if (code != ErrorCode.SUCCESS) {
                            if (code == ErrorCode.ERROR_COMPONENT_NOT_INSTALLED) {
                                //未安装则跳转到提示安装页面
                            } else {
                                showTip("语音合成失败,错误码: " + code);
                            }
                        }
                    } else { //recording mode
                        releaseMp3Player();
                        previewRecordedAudio();
                    }
                }

                break;
            case R.id.save_and_upload_btn:
                uploadAudioFile(TTS_AUDIO_PATH.replace(".wav", ".mp3"));
                break;
            case R.id.record_state_btn:
                switch (RECORING_STATE) {
                    case PRE_RECORDING:
                        tryListenOnline = false;
                        RECORING_STATE = RecordingState.RECORDING;
                        mRecordStateBtn.setText("完成");

                        mRecorder = new MediaRecorder();

                        mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
                        mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
                        mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
                        mRecorder.setOutputFile(RECORDING_AUDIO_PATH);

                        MediaRecorder.OnErrorListener errorListener = null;
                        mRecorder.setOnErrorListener(errorListener);
                        MediaRecorder.OnInfoListener infoListener = null;
                        mRecorder.setOnInfoListener(infoListener);

                        try {
                            mRecorder.prepare();
                            mRecorder.start();
                            startCountdownTimer();
                            isRecording = true; // we are currently recording
                        } catch (IllegalStateException e) {
                            e.printStackTrace();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        handler.post(updateVisualizer);
                        break;
                    case RECORDING:
                        RECORING_STATE = RecordingState.STOP_RECORDING;
                        mRecordStateBtn.setText("保存");
                        isRecording = false;

                        releaseRecorder();

                        new Thread() {
                            @Override
                            public void run() {
                                convert2Mp3(RECORDING_AUDIO_PATH);
                            }
                        }.start();
                        break;
                    case STOP_RECORDING:
                        RECORING_STATE = RecordingState.PRE_RECORDING;
                        mRecordStateBtn.setText("开始录音");
                        //uploadAudioFile(RECORDING_AUDIO_PATH);
                        uploadAudioFile(RECORDING_AUDIO_PATH.replace(".amr", ".mp3"));
                        break;
                    default:
                        break;
                }
                break;
            case R.id.retry_record_tv:
                mRecordStateBtn.setText("开始录音");
                RECORING_STATE = RecordingState.PRE_RECORDING;
                isRecording = false;
                mRecordVisualizerView.clear();
                mRecordVisualizerView.postInvalidate();
                releaseRecorder();
                releaseMp3Player();
                break;
            default:
                break;
        }
    }

    private void convert2Mp3(String sourceFile) {
        if (Tools.isEmpty(sourceFile)) {
            //showTip("音频文件名为空！");
            return;
        }

        File wavFile = new File(sourceFile);
        if (!wavFile.exists()) {
            showTip("生成音频文件失败，请重新试听！");
            return;
        }

        IConvertCallback callback = new IConvertCallback() {
            @Override
            public void onSuccess(File convertedFile) {
                Toast.makeText(AddHabitClockActivity.this, "成功生成语音文件" + convertedFile.getPath(), Toast.LENGTH_LONG).show();
            }

            @Override
            public void onFailure(Exception error) {
                // Toast.makeText(AddHabitClockActivity.this, "ERROR: " + error.getMessage(), Toast.LENGTH_LONG).show();
            }
        };
        //  Toast.makeText(this, "Converting audio file...", Toast.LENGTH_SHORT).show();
        AndroidAudioConverter.with(this)
                .setFile(wavFile)
                .setFormat(AudioFormat.MP3)
                .setCallback(callback)
                .convert();
    }

    private void publishCustomHabit() {
        if (Tools.isEmpty(LOCAL_HABIT_IMAGE) && Tools.isEmpty(imgUrl_toSubmit)) {
            showTip("您还没有选择图像!");
            return;
        }
        if (Tools.isEmpty(mTitleEt.getText().toString())) {
            showTip("您还没有填写习惯标题!");
            return;
        }

        if (!mSetTimerTv.getText().toString().contains(":")) {
            showTip("您还没有设置时间!");
            return;
        }

        if (!isEdit && Tools.isEmpty(mp3url_toSubmit)) {
            showTip("请上传或选择音频文件");
            return;
        }

        if (isEdit) { // 编辑模式
//            if (Tools.isNotEmpty(LOCAL_HABIT_IMAGE) && !LOCAL_HABIT_IMAGE.contains("api.jdy520.com")
//                    || Tools.isNotEmpty(LOCAL_HABIT_IMAGE) && !LOCAL_HABIT_IMAGE.contains("api.lexiaobao.net")) {

            if (Tools.isNotEmpty(LOCAL_HABIT_IMAGE)
                    && Tools.isNotEmpty(imgUrl_toSubmit) && !LOCAL_HABIT_IMAGE.equals(imgUrl_toSubmit)) {
                uploadImageFile(LOCAL_HABIT_IMAGE);
                Log.i("test", "上传图片");

            } else {
                Log.i("test", "修改");
                modifyCustomHabit(mTitleEt.getText().toString(), mSetTimerTv.getText().toString());
            }
        } else { // 创建模式
            if (Tools.isNotEmpty(LOCAL_HABIT_IMAGE) && !LOCAL_HABIT_IMAGE.contains("api.jdy520.com")
                    || Tools.isNotEmpty(LOCAL_HABIT_IMAGE) && !LOCAL_HABIT_IMAGE.contains("api.lexiaobao.net")) {
                uploadImageFile(LOCAL_HABIT_IMAGE); // 上传头像

                Log.i("test", "上传图片");
            } else {

                Log.i("test", "创建");
                if (Tools.isEmpty(mp3url_toSubmit)) {
                    if (mCurrentSelectedEnum == SelectedEnum.CustomContent) {
                        String audioFilePath = "";
                        audioFilePath = TTS_AUDIO_PATH; // TTS
                        uploadAudioFile(TTS_AUDIO_PATH.replace(".wav", ".mp3"));
                    } else if (mCurrentSelectedEnum == SelectedEnum.Recording) {
                        String audioFilePath = "";
                        audioFilePath = RECORDING_AUDIO_PATH; // 录音
                        uploadAudioFile(RECORDING_AUDIO_PATH.replace(".amr", ".mp3"));
                    }
                    if (mCurrentSelectedEnum == SelectedEnum.StoryBabysong) {
                        if (ai != null) {
                            mp3url_toSubmit = ai.url;
                        }
                    } else {
                        if (ldi != null) {
                            mp3url_toSubmit = ldi.av;
                        }
                    }
                } else {
                    submitCustomHabit(mTitleEt.getText().toString(), mSetTimerTv.getText().toString());
                }
            }
        }
    }

    // 修改习惯
    private void modifyCustomHabit(final String title, final String time) {
        new CustomAsyncTask(this, new IAsyncTask() {
            @Override
            public void onRecieveData(Activity activity, ResponseResult result) {

                dismissLoading();
                if (result.isSuccess()) {
                    toastShow("修改成功");
                    Intent resultIntent = new Intent();
                    setResult(RESULT_OK, resultIntent);
                    finish();
                } else {
                    dismissLoading();
                    toastShow(result.data);


                }
            }

            @Override
            public ResponseResult doInbackground(Activity activity) {
                HashMap<String, Object> param_ = new HashMap<String, Object>();
                param_.put(HttpUtils.TAG_SNO_I, leUser.sno);

                if (Tools.isNotEmpty(imgUrl_toSubmit)) {
                    param_.put("img", imgUrl_toSubmit);
                }

                if (Tools.isNotEmpty(mp3url_toSubmit)) {
                    param_.put("mp3_url", mp3url_toSubmit);
                }

                param_.put("name", title);
                param_.put("time", time);

                param_.put(HttpUtils.TAG_KEY_I, HttpUtils.KEY);
                return HttpUtils
                        .startRequest(HttpUtils.API_URL + "/api/2.0/operation/habit/habits_customized/" + mPainPointItem.id,
                                param_, HttpUtils.TAG_PUT_REQUEST);

            }
        }).execute("请检查网络连接!");
    }

    private void uploadImageFile(final String filePath) {
        showloading("");
        new CustomAsyncTask(this, new IAsyncTask() {
            @Override
            public void onRecieveData(Activity activity, ResponseResult result) {
                if (result.isSuccess()) {
                    imgUrl_toSubmit = result.data;
                    if (Tools.isEmpty(mp3url_toSubmit)) {
                        String audioFilePath = "";
                        if (mCurrentSelectedEnum == SelectedEnum.CustomContent) {
                            audioFilePath = TTS_AUDIO_PATH; // TTS
                            uploadAudioFile(TTS_AUDIO_PATH.replace(".wav", ".mp3"));
                        } else if (mCurrentSelectedEnum == SelectedEnum.Recording) {
                            audioFilePath = RECORDING_AUDIO_PATH; // 录音
                            uploadAudioFile(RECORDING_AUDIO_PATH.replace(".amr", ".mp3"));
                        }
                        if (mCurrentSelectedEnum == SelectedEnum.StoryBabysong) {
                            if (ai != null) {
                                mp3url_toSubmit = ai.url;
                            }
                        } else {
                            if (ldi != null) {
                                mp3url_toSubmit = ldi.av;
                            }
                        }
                    } else {
                        if (isEdit) {
                            modifyCustomHabit(mTitleEt.getText().toString(), mSetTimerTv.getText().toString());
                        } else {
                            submitCustomHabit(mTitleEt.getText().toString(), mSetTimerTv.getText().toString());
                        }
                    }
                } else {
                    dismissLoading();
                    toastShow(result.data);
                }
            }

            @Override
            public ResponseResult doInbackground(Activity activity) {
                HashMap<String, Object> param_ = new HashMap<String, Object>();
                param_.put(HttpUtils.TAG_KEY_I, HttpUtils.KEY);
                param_.put(HttpUtils.TAG_MOBILE_I, leUser.id);
                param_.put(HttpUtils.TAG_MODULE_I, "custom_habits/img");
                return HttpUtils.startUploadRequest(HttpUtils.API_URL
                                + HttpUtils.UPLOAD_BABY_AVATAR_POST, param_, "Filedata", filePath,
                        HttpUtils.TAG_POST_REQUEST);

            }
        }).execute("请检查网络连接!");
    }

    private void uploadAudioFile(final String filePath) {
        if (Tools.isEmpty(filePath)) {
            return;
        }
        File file = new File(filePath);
        if (!file.exists()) {
            showTip("请先进行试听，生成音频文件!");
            return;
        }

        showloading("");

        new CustomAsyncTask(this, new IAsyncTask() {
            @Override
            public void onRecieveData(Activity activity, ResponseResult result) {
                if (result.isSuccess()) {
                    mp3url_toSubmit = result.data;
                    toastShow("上传成功");
                } else {
                    toastShow(result.data);
                }
                dismissLoading();
            }

            @Override
            public ResponseResult doInbackground(Activity activity) {

                HashMap<String, Object> param_ = new HashMap<String, Object>();
                param_.put(HttpUtils.TAG_KEY_I, HttpUtils.KEY);
                param_.put(HttpUtils.TAG_MOBILE_I, leUser.id);
                param_.put(HttpUtils.TAG_MODULE_I, "custom_habits/audio");
                return HttpUtils.startUploadRequest(HttpUtils.API_URL
                                + HttpUtils.UPLOAD_BABY_AVATAR_POST, param_, "Filedata", filePath,
                        HttpUtils.TAG_POST_REQUEST);

            }
        }).execute("请检查网络连接!");
    }


    private String mp3url_Online, mp3url_toSubmit, imgUrl_toSubmit;

    private void submitCustomHabit(final String title, final String time) {
        new CustomAsyncTask(this, new IAsyncTask() {
            @Override
            public void onRecieveData(Activity activity, ResponseResult result) {
                dismissLoading();
                if (result.isSuccess()) {
                    toastShow("提交成功");
                    Intent resultIntent = new Intent();
                    setResult(RESULT_OK, resultIntent);
                    finish();
                } else {
                    dismissLoading();
                    toastShow(result.data);
                }
            }

            @Override
            public ResponseResult doInbackground(Activity activity) {
                HashMap<String, Object> param_ = new HashMap<String, Object>();
                param_.put(HttpUtils.TAG_SNO_I, leUser.sno);
                if (Tools.isNotEmpty(imgUrl_toSubmit)) {
                    param_.put("img", imgUrl_toSubmit);
                }

                if (Tools.isNotEmpty(mp3url_toSubmit)) {
                    param_.put("mp3_url", mp3url_toSubmit);
                }

                if (Tools.isNotEmpty(title)) {
                    param_.put("name", title);
                }

                if (Tools.isNotEmpty(time)) {
                    param_.put("time", time);
                }

                param_.put(HttpUtils.TAG_KEY_I, HttpUtils.KEY);
                return HttpUtils
                        .startRequest(HttpUtils.API_URL + "/api/2.0/operation/habit/habits_customized",
                                param_, HttpUtils.TAG_POST_REQUEST);

            }
        }).execute("请检查网络连接!");
    }


    private MediaPlayer.OnCompletionListener mediaPlayerListener = new MediaPlayer.OnCompletionListener() {
        @Override
        public void onCompletion(MediaPlayer mp) {
            stopAnimation();
        }
    };


    private MediaPlayer.OnCompletionListener mediaPlayerListener2 = new MediaPlayer.OnCompletionListener() {
        @Override
        public void onCompletion(MediaPlayer mp) {
            stopAnimation2();
        }
    };

    private void previewRecordedAudio() {
        if (mTts != null && mTts.isSpeaking()) {
            mTts.stopSpeaking();
        }
        if (mp3Player == null)
            mp3Player = new MediaPlayer();
        try {
            mp3Player.setDataSource(RECORDING_AUDIO_PATH);
            mp3Player.prepare();
            mp3Player.start();
            startAnimation();
            mp3Player.setOnCompletionListener(mediaPlayerListener);
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (SecurityException e) {
            e.printStackTrace();
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void releaseMp3Player() {
        if (mp3Player != null) {
            mp3Player.stop();
            mp3Player.setOnCompletionListener(null);
            mp3Player.release();
            mp3Player = null;
        }
    }


    // updates the visualizer every 50 milliseconds
    Runnable updateVisualizer = new Runnable() {
        @Override
        public void run() {
            if (isRecording) // if we are already recording
            {
                // get the current amplitude
                int x = mRecorder.getMaxAmplitude();
                mRecordVisualizerView.addAmplitude(x); // update the VisualizeView
                mRecordVisualizerView.invalidate(); // refresh the VisualizerView

                // update in 40 milliseconds
                handler.postDelayed(this, REPEAT_INTERVAL);
            }
        }
    };

    /**
     * 初始化监听。
     */
    private InitListener mTtsInitListener = new InitListener() {
        @Override
        public void onInit(int code) {
            Log.d(TAG, "InitListener init() code = " + code);
            if (code != ErrorCode.SUCCESS) {
                showTip("初始化失败,错误码：" + code);
            } else {
                // 初始化成功，之后可以调用startSpeaking方法
                // 注：有的开发者在onCreate方法中创建完合成对象之后马上就调用startSpeaking进行合成，
                // 正确的做法是将onCreate中的startSpeaking调用移至这里
            }
        }
    };


    /**
     * 参数设置
     *
     * @return
     */
    private void setParam() {
        // 清空参数
        mTts.setParameter(SpeechConstant.PARAMS, null);
        // 根据合成引擎设置相应参数
        if (mEngineType.equals(SpeechConstant.TYPE_CLOUD)) {
            mTts.setParameter(SpeechConstant.ENGINE_TYPE, SpeechConstant.TYPE_CLOUD);
            // 设置在线合成发音人
            mTts.setParameter(SpeechConstant.VOICE_NAME, voicer);
            //设置合成语速
            mTts.setParameter(SpeechConstant.SPEED, "50");
            //设置合成音调
            mTts.setParameter(SpeechConstant.PITCH, "50");
            //设置合成音量
            mTts.setParameter(SpeechConstant.VOLUME, "50");
        } else {
            mTts.setParameter(SpeechConstant.ENGINE_TYPE, SpeechConstant.TYPE_LOCAL);
            // 设置本地合成发音人 voicer为空，默认通过语记界面指定发音人。
            mTts.setParameter(SpeechConstant.VOICE_NAME, "");
            /**
             * TODO 本地合成不设置语速、音调、音量，默认使用语记设置
             * 开发者如需自定义参数，请参考在线合成参数设置
             */
        }
        //设置播放器音频流类型
        mTts.setParameter(SpeechConstant.STREAM_TYPE, "3");
        // 设置播放合成音频打断音乐播放，默认为true
        mTts.setParameter(SpeechConstant.KEY_REQUEST_FOCUS, "true");

        // 设置音频保存路径，保存音频格式支持pcm、wav，设置路径为sd卡请注意WRITE_EXTERNAL_STORAGE权限
        // 注：AUDIO_FORMAT参数语记需要更新版本才能生效
        mTts.setParameter(SpeechConstant.AUDIO_FORMAT, "wav");
        mTts.setParameter(SpeechConstant.TTS_AUDIO_PATH, TTS_AUDIO_PATH);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        releaseRecorder();

        releaseMp3Player();

        if (null != mTts) {
            mTts.stopSpeaking();
            // 退出时释放连接
            mTts.destroy();
        }
    }

    private void releaseRecorder() {
        stopCountdownTimer();
        if (mRecorder != null) {
            isRecording = false; // stop recording
            handler.removeCallbacks(updateVisualizer);
            mRecordVisualizerView.clear();
            mRecorder.stop();
            mRecorder.reset();
            mRecorder.release();
            mRecorder = null;
        }
    }

    /**
     * 合成回调监听。
     */
    private SynthesizerListener mTtsListener = new SynthesizerListener() {

        @Override
        public void onSpeakBegin() {
            //showTip("开始播放");
            startAnimation();
        }

        @Override
        public void onSpeakPaused() {
            showTip("暂停播放");
            stopAnimation();
        }

        @Override
        public void onSpeakResumed() {
            showTip("继续播放");
            startAnimation();
        }

        @Override
        public void onBufferProgress(int percent, int beginPos, int endPos,
                                     String info) {
            // 合成进度
            mPercentForBuffering = percent;
            showTip(String.format("正在合成语音%d%%",
                    mPercentForBuffering));
        }

        @Override
        public void onSpeakProgress(int percent, int beginPos, int endPos) {
            // 播放进度
            mPercentForPlaying = percent;
//            showTip(String.format(getString(R.string.tts_toast_format),
//                    mPercentForBuffering, mPercentForPlaying));
        }

        @Override
        public void onCompleted(SpeechError error) {
            if (error == null) {
//                showTip("已完成语音合成");
                convert2Mp3(TTS_AUDIO_PATH);
            } else if (error != null) {
                showTip(error.getPlainDescription(true));
            }
            stopAnimation();
        }

        @Override
        public void onEvent(int eventType, int arg1, int arg2, Bundle obj) {
            // 以下代码用于获取与云端的会话id，当业务出错时将会话id提供给技术支持人员，可用于查询会话日志，定位出错原因
            // 若使用本地能力，会话id为null
            //	if (SpeechEvent.EVENT_SESSION_ID == eventType) {
            //		String sid = obj.getString(SpeechEvent.KEY_EVENT_SESSION_ID);
            //		Log.d(TAG, "session id =" + sid);
            //	}
        }
    };

    private void showTip(final String str) {
        mToast.setText(str);
        mToast.show();
    }


    /**
     * 设置每次启动时间
     */
    private void setHabitTime() {
        CustomTimeDialog.Builder customBuilder = new CustomTimeDialog.Builder(
                this);
        customBuilder.setTitle("设置每次启动时间")
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                }).setPositiveButton("确定", new CustomTimeDialog.Builder.OnOkClickListener() {
            @Override
            public void onClickOk(final int hourOfDay, final int minute) {

                String text = String.format("%02d", hourOfDay) + ":"
                        + String.format("%02d", minute);

                mSetTimerTv.setText(text);

                timeDlg.dismiss();

            }
        });

        if (!this.isFinishing()) {
            timeDlg = customBuilder.create();
            timeDlg.show();
        }
    }
}
